import 'package:flutter/services.dart';
import '../../generated/assets.dart';
import '../channel/app_type.dart';

class AssetsUtils {
  const AssetsUtils._();

  static final Map<String, bool> _assetCache = {};

  // 检查资源文件是否存在，优先从缓存中获取
  static Future<bool> assetExistsAsync(String path) async {
    if (_assetCache.containsKey(path)) {
      return _assetCache[path]!;
    }

    // 如果不在缓存中，进行异步检查并缓存结果
    Future<bool> checkAssetExists() async {
      try {
        await rootBundle.load(path);
        _assetCache[path] = true;
        return true;
      } catch (_) {
        _assetCache[path] = false;
        return false;
      }
    }

    // 使用 Future.sync 来同步执行异步操作
    return Future.sync(() => checkAssetExists()).then((value) => value);
  }

  // 检查资源文件是否存在
  static bool assetExists(String path) {
    return Assets.assetsMap.contains(path);
  }

  //转换成夜间模式的资源路径
  static String getDarkAssetPath(String path) {
    final newPath = path.replaceAll('assets/svg/', 'assets/svg/dark/')..replaceAll('assets/img/', 'assets/img/dark/');
    if (assetExists(newPath)) {
      return newPath;
    }
    return path;
  }

  //转换成渠道包的资源路径
  static String getAppTypeAssetPath(String path) {
    final newPath = path.replaceAll('assets/svg/', 'assets/svg/${appType.name}/')..replaceAll('assets/img/', 'assets/img/${appType.name}/');
    if (assetExists(newPath)) {
      return newPath;
    }
    return path;
  }
}
